package com.shengwei.truck.driver.view.ui;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModel;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.shengwei.truck.driver.bean.AppInfo;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.utils.NotificationUtils;
import com.shengwei.truck.driver.utils.UpdateApp;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.databinding.ActivityMainBinding;
import com.shengwei.truck.driver.permission.MyLocationRequestPermission;
import com.shengwei.truck.driver.permission.RequestPermissionResult;
import com.shengwei.truck.driver.socket.SocketService;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.ui.home.FragmentFactory;
import com.shengwei.truck.driver.view.ui.settings.SettingsActivity;
import com.tbruyelle.rxpermissions2.Permission;

import org.apache.log4j.chainsaw.Main;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.List;
import cn.jpush.android.api.NotificationMessage;

/**
 *
 * 首页框架，底部4个TAB页分别对应4个Fragment
 */
public class MainActivity extends BaseActivity<ViewModel, ActivityMainBinding> implements RequestPermissionResult {
    private String TAG = "MainActivity";
    private BottomNavigationBar mBottomNavigationBar;
    public static int mCurTabIndex = 0;
    private long mBackTimes = 0;
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    public static boolean isForeground = false;

    //接受自定义消息（透传消息，SDK不会自动展示通知栏）
    public static final String KEY_EXTRAS = "extras";
    public static final String KEY_MESSAGE = "message";
    public static final String MESSAGE_RECEIVED_ACTION = "cn.jiguang.demo.jpush.MESSAGE_RECEIVED_ACTION";
    //检查更新
    private NotificationManager mNotificationManager;
    private Notification mNotification;

    //该接口MyLocationRequestPermission由MapFragment实现，MainActivity使用这个接口接口实例来回调MapFragment传达定位权限申请结果
    private  MyLocationRequestPermission mMyLocationRequestPermission;
    public void setMyLocationRequestPermission(MyLocationRequestPermission myLocationRequestPermission) {
        this.mMyLocationRequestPermission = myLocationRequestPermission;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStart() {
        MyLogCat.i(TAG,"onStart");
       // startService();
        if(MyApplication.UPDATE_STATE == 0)
            checkUpdate(UpdateApp.CHECK_AND_DOWNLOAD);
        super.onStart();
    }


    /**
     * 检查新版本
     * @param checkType 0只检查新版本, 如果有则显示小红点;
     *                  1 点击“检查新版本”并弹出升级提示框
     */
    private void checkUpdate(final int checkType) {

        final UpdateApp updateApp = new UpdateApp(this);
        updateApp.checkUpdate(checkType, new UpdateApp.GetAppInfoListener() {
            @Override
            public void onSuccess(AppInfo appInfo, int checkType) {

                if(checkType == 1)  //点击升级
                {
                    if(appInfo.getHaveNewVersion() == 1)  //如果有新版本，则去下载
                    {
                        String downloadUrl = appInfo.getDownloadUrl();
                        String updateContent = appInfo.getUpContent();
                        updateApp.downLoad(downloadUrl,updateContent,new MyDownLoadListener());
                    }
                }
            }
            @Override
            public void onFailed(String errMsg) {
                String tip;

                if(!TextUtils.isEmpty(errMsg) && !(errMsg.contains("未检查到"))) {
                    tip = errMsg;
                }
                else
                {
                    tip = "已经是最新版本了";
                }

                if(checkType == 1)
                    Toast.makeText(MainActivity.this,tip,Toast.LENGTH_SHORT).show();

            }
        });
    }


    /**
     * 构建Notification，以保证后台连续定位
     * @return
     */
    public Notification buildNotification() {
        Notification notification;
        String notifyTitle = this.getResources().getString(R.string.notify_title);
        String notifyContent = this.getResources().getString(R.string.notify_content);
        NotificationUtils mNotificationUtils;
        //设置后台定位
        if (Build.VERSION.SDK_INT >= 26) {  //AndroidO及以上系统
            mNotificationUtils = new NotificationUtils(this);
            Notification.Builder builder2 = mNotificationUtils.getAndroidChannelNotification(notifyTitle, notifyContent);
            builder2.setOnlyAlertOnce(true);
            builder2.setOngoing(true);
            builder2.setTicker("来回好运");
            builder2.setSound(null);
            builder2.setVibrate(null);
            builder2.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);//取消震动,铃声其他都不好使
            notification = builder2.build();

        } else {
            mNotificationUtils = new NotificationUtils(this,true);
            Notification.Builder builder = mNotificationUtils.getAndroidNotification (notifyTitle, notifyContent);
            notification = builder.build(); // 获取构建好的Notification
        }
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        notification.contentView = new RemoteViews(this.getPackageName(), R.layout.update_notify);
        return notification;
    }

    //检查更新START
    /**
     * 初始化通知栏上的APP升级进度条
     */
    public void initNotifyBarUpdate() {
        mNotification = buildNotification();
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    }
    /**
     * 监控安装包下载进度
     */

    public class MyDownLoadListener implements UpdateApp.DownLoadListener {

        @Override
        public void onSuccess() {
            //更新通知栏进度条
            if(mNotificationManager != null){
                mNotification.contentView.setTextViewText(R.id.content_view_text1, "下载完成！");
                mNotification.contentView.setProgressBar(R.id.content_view_progress, 100, 100, false);
                mNotificationManager.cancel(101);
            }
            MyApplication.UPDATE_STATE = 0; //未正在更新
        }

        @Override
        public void onFailed() {
            if(mNotificationManager != null) {
                mNotificationManager.cancel(101);
            }
            MyApplication.UPDATE_STATE = 0; //未正在更新
            Toast.makeText(MainActivity.this,"下载失败",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onProgress(int progress) {
            if(mNotificationManager != null) {
                mNotification.contentView.setTextViewText(R.id.content_view_text1, "正在下载...  " + progress + "%");
                mNotification.contentView.setProgressBar(R.id.content_view_progress, 100, progress, false);
                mNotificationManager.notify(101, mNotification);
            }
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onResume() {
        MyLogCat.i(TAG,"onResume");
        isForeground = true;
        String content = "gaoxiaowei";
       //gxw- HomeToast.showText(this.getApplicationContext(),content);
        super.onResume();
    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetNofity(NotificationMessage message) {
        String content = message.notificationContent;
       //gxw- HomeToast.showText(this.getApplicationContext(),content);
    }

    /**
     * 启动后台服务
     */
    public void startService() {
        if (Build.VERSION.SDK_INT >= 26) {
            Intent bleSvcIntent = new Intent(this, SocketService.class);
            this.startForegroundService(bleSvcIntent);
        } else {
            Intent bleSvcIntent = new Intent(this, SocketService.class);
            this.startService(bleSvcIntent);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        getIntent().putExtras(intent);
        int tabIndex = intent.getIntExtra("tabIndex",0);
        MyLogCat.e(TAG, "onNewIntent执行 tabIndex="+tabIndex);
        clearAllFragment();
        mBottomNavigationBar.selectTab(tabIndex);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    /**
     * 初始化UI控件
     */
    public void initView() {
        initBottomNavigationBar();
        initFirstFragment(0);
        //检测通知开关是否打开返：1表示开启，0表示关闭，-1表示检测失败
    /*    int ret = JPushInterface.isNotificationEnabled(getApplicationContext());
        if(ret == 0){
            JPushInterface.goToAppNotificationSettings(getApplicationContext());
        }*/
    }


    /**
     * 清4个底部TAB所有fragment
     */
    public void clearAllFragment() {
        FragmentManager mFragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        //Step1.移除缓存的Fragment
        List<Fragment> fragments = mFragmentManager.getFragments();
        if (fragments != null && fragments.size() > 0) {
            //说明有之前缓存的fragment 处理fragment重影的问题
            for (int i = 0; i < fragments.size(); i++) {
                transaction.remove(fragments.get(i));
            }
             transaction.commit();
        }
        FragmentFactory.homeFragment = null;
        FragmentFactory.taskFragment = null;
        FragmentFactory.mapFragment = null;
        FragmentFactory.mineFragment = null;
    }
    /**
     * 添加第一个Fragment：homeFragment
     */
    private void initFirstFragment(int position) {
        clearAllFragment();
        //Step2.添加第一个Fragment：homeFragment
        FragmentManager mFragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        Fragment fragment = FragmentFactory.getFragment(position,mFragmentManager);
        if (fragment.isAdded()) {
            transaction.show(fragment).commit();
        }
        else{
            transaction.add(R.id.fl_container, fragment, String.valueOf(position)).commit();
        }
    }

    /**
     * 初始化底部导航栏
     */
    private void initBottomNavigationBar() {

        //mBottomNavigationBar添加Item选项卡
       mBottomNavigationBar = (BottomNavigationBar) this.findViewById(R.id.bottom_navigation_bar);
        mBottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        mBottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
        mBottomNavigationBar
                .addItem(new BottomNavigationItem(R.drawable.btn_mainnav_home_pressed, R.string.bottom_tab_home)
                        .setInactiveIconResource(R.drawable.btn_mainnav_home_normal))//设置未选中时的颜色

                .addItem(new BottomNavigationItem(R.drawable.btn_mainnav_task_pressed, R.string.bottom_tab_task)
                        .setInactiveIconResource(R.drawable.btn_mainnav_task_normal))//设置未选中时的颜色

                .addItem(new BottomNavigationItem(R.drawable.btn_mainnav_map_pressed, R.string.bottom_tab_map)
                        .setInactiveIconResource(R.drawable.btn_mainnav_map_normal))//设置未选中时的颜色

                .addItem(new BottomNavigationItem(R.drawable.btn_mainnav_mine_pressed, R.string.bottom_tab_mine)
                        .setInactiveIconResource(R.drawable.btn_mainnav_mine_normal))//设置未选中时的颜色

                .setBarBackgroundColor(R.color.white)//设置背景色
                .setFirstSelectedPosition(0)//默认选择索引为0的菜单
                .setActiveColor(R.color.colorPrimary)
                .setInActiveColor(R.color.inactive_color_bottom_tab)
                .initialise();//初始化




        //选中mBottomNavigationBar某一个Tab选项卡时，显示Fragment，否则隐藏。
        mBottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                Fragment fragment = FragmentFactory.getFragment(position,fragmentManager);
                if (fragment != null && fragment.isAdded()) {
                    transaction.show(fragment).commit();
                } else {
                    transaction.add(R.id.fl_container, fragment, String.valueOf(position)).commitAllowingStateLoss();
                }
                mCurTabIndex = position;
            }
            @Override
            public void onTabUnselected(int position) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.hide(FragmentFactory.getFragment(position,fragmentManager)).commit();
            }
            @Override
            public void onTabReselected(int position) {
                int i = 0;
            }
        });
    }

    /**
     * 按两次返回退出APP
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - mBackTimes > 2000) {
                    //如果两次按键时间间隔大于2秒，则不退出
                    MyToast.showToastCenter(new WeakReference<>(MainActivity.this),"再次点击将退出程序",Toast.LENGTH_SHORT,true);
                    mBackTimes = secondTime;//更新firstTime
                    return true;
                } else {
                    finish();
                    ActivityCollectorUtil.finishAllActivity();
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 由于RxPermissions()构造函数只能接收Activity，所以
     * 在Activity里实现RequestPermissionResult接口中的以下两个函数，最终权限的申请结果将回调到MainActivity里的
     * onPermissionGranted与onPermissionDenied，然后再以回调的方式将结果传递到Fragment里，当然Fragment里要实现Activity中定义的接口
     *  MyLocationRequestPermission;。
     *
     * onPermissionGranted 权限申请被允许时，回调到此接口函数
     * @param permission：正在申请的权限信息，比如权限名。
     *
     */
    @Override
    public void onPermissionGranted(Permission permission) {

        switch (permission.name) {
            case Manifest.permission.ACCESS_FINE_LOCATION:

                //拥有了位置权限还不够，需要检查GPS服务开关是否被打开，如果没有打开，则跳转到“GPS位置服务开关”页面去设置。
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkLocationServiceIsOpen()) {
                    AlertDialog.Builder gpsDlgBuilder = new AlertDialog.Builder(this);
                    gpsDlgBuilder.setTitle(R.string.location_service_enable_false)
                            .setMessage(R.string.location_service_enable_tip_msg)
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    })
                            .setPositiveButton(R.string.settings,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false);
                    AlertDialog gpsDidlog = gpsDlgBuilder.create();
                    gpsDidlog.show();
                    int colorPrimary = MainActivity.this.getResources().getColor(R.color.colorPrimary);
                    int colorDescribe = MainActivity.this.getResources().getColor(R.color.describe_color);
                    gpsDidlog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(colorPrimary);
                    gpsDidlog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(colorDescribe);
                } else {
                    //位置权限及GPS位置服务开关都打开，则可以定位了，通知给MapFragment
                    mMyLocationRequestPermission.onGranted();
                }
                break;
        }
    }

    /**
     * onPermissionDenied 权限申请被拒绝，回调到此接口函数
     * @param permission
     * @param DeniedType：拒绝类型：1 拒绝；2禁止，以后不再提醒；3 位置服务开关没有打开（这个适用于定位权限的申请）
     */
    @Override
    public void onPermissionDenied(Permission permission, int DeniedType) {
        mMyLocationRequestPermission.onDenied(DeniedType);
    }

    /**
     * 位置权限申请成功后，还要打开“GPS位置服务开关”
     * 从“GPS位置服务开关”打开页面，返回到MainActivity里，然后检查“GPS位置服务开关”是否确实打开了，
     * 并将整个位置权限申请的成功与失败通知给MapFragment。
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_OPEN_GPS) {
            if(checkLocationServiceIsOpen()) {
                mMyLocationRequestPermission.onGranted();
            }
            else {
                mMyLocationRequestPermission.onDenied(3);
            }
        }
    }

    /**
     * 检查"GPS位置服务开关"是否打开
     * @return  true:打开，false:没有打开
     */
    private boolean checkLocationServiceIsOpen() {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }
}
